/*
 * Copyright (C) 2012 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.ui;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.network.ApiAsyncTask;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.TopBar;
import com.mol.market.common.util.Utils;
import com.mol.market.common.vo.TagsInfo;
import com.mol.market.common.widget.AppListAdapter;
import com.mol.market.common.widget.AppListAdapter.ViewBinder;
import com.mol.market.common.widget.BaseActivity;
import com.mol.market.common.widget.CategoryTagView;
import com.mol.market.common.widget.CategoryTagView.TagViewListener;
import com.mol.market.common.widget.LoadingDrawable;

/**
 * 标签页
 * @author Chaos	
 * @since 0.9.6
 * @date 2012-10-16
 *
 */
public class CategoryTagsActivity extends BaseActivity implements ApiAsyncTask.ApiRequestListener,OnClickListener,
        TagViewListener{
    
    private ListView mRecommendList;
    private AppListAdapter mRecommendAdapter;
    private FrameLayout mLoading;
    private ProgressBar mProgress;
    private TextView mNoData;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category_tags);
        
        initTopBar();
        initListView();
        
        IntentFilter themeFilter = new IntentFilter(Constants.BROADCAST_CHANGE_THEME);
        registerReceiver(mThemeReceiver, themeFilter);

//TODO        MarketAPI.getCategoryTags(getApplicationContext(), this);
    }
    
    // 检查用户是否更换主题
    private BroadcastReceiver mThemeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            TopBar.initSkin(mSession, CategoryTagsActivity.this);
        }
    };
    
    /**
     * 初始化Topbar
     */
    private void initTopBar() {
        TopBar.createTopBar(
                mSession, 
                this, 
                new View[] { 
                        findViewById(R.id.top_bar_title),
                        findViewById(R.id.top_bar_search) }, 
                new int[] { 
                        View.VISIBLE, 
                        View.VISIBLE },
                getString(R.string.category_tags));
    }
    
    private void initListView(){
        mRecommendList = (ListView) findViewById(android.R.id.list);
        mLoading = (FrameLayout) findViewById(R.id.loading);
        mProgress = (ProgressBar) findViewById(R.id.progressbar);
        mProgress.setIndeterminateDrawable(new LoadingDrawable(getApplicationContext()));
        mProgress.setVisibility(View.VISIBLE);
        mNoData = (TextView) findViewById(R.id.no_data);
        mNoData.setOnClickListener(this);
        mRecommendList.setEmptyView(mLoading);
        
        mRecommendAdapter = new AppListAdapter(this,
                null,
                R.layout.activity_category_tags_list,
                new String[]{
                    Constants.KEY_GROUP_NAME,
                    Constants.KEY_TAGS},
                new int[]{
                    R.id.tv_title,
                    R.id.tag_item});
        
        mRecommendAdapter.setViewBinder(new ViewBinder() {
            @Override
            public boolean setViewValue(View view, Object data, int position, Object textRepresentation) {
                
                if(view.getId() == R.id.tag_item){
                    CategoryTagView category = (CategoryTagView)view;
                    category.setTagsViewOnClickListener(CategoryTagsActivity.this);
                    category.changeTags((List<TagsInfo>) textRepresentation);
                    return true;
                }
                return false;
            }
        });
        
        mRecommendList.setAdapter(mRecommendAdapter);
    }

    @Override
    public void onSuccess(int method, Object obj) {
        switch (method) {
        case MarketAPI.ACTION_GET_CATEGORY_TAGS:
            mRecommendAdapter.addDataList((ArrayList<HashMap<String, Object>>) obj);
            break;
        }
        
    }

    @Override
    public void onError(int method, int statusCode) {
        switch (method) {
        case MarketAPI.ACTION_GET_CATEGORY_TAGS:
            mNoData.setVisibility(View.VISIBLE);
            mProgress.setVisibility(View.GONE);
            break;
        }
    }

    @Override
    public void onClick(View v) {
        //重试
        mNoData.setVisibility(View.GONE);
        mProgress.setVisibility(View.VISIBLE);
        
        //API重新请求
//TODO        MarketAPI.getCategoryTags(getApplicationContext(), this);
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mThemeReceiver);
    }

    @Override
    public void onTagsViewClick(View v, TagsInfo tag) {
        if(tag == null){
            //unlucky
            return ;
        }

        Utils.trackEvent(this, Constants.TAG,
          String.format(Constants.CLICK_TAG, tag.getTagName()));
        Utils.jumpToPage(this, 
                TagsListActivity.class, 
                false, 
                new String[] {
                    TagsListActivity.TAGS_ID, 
                    TagsListActivity.TAGS_NAME },
                new Serializable[] { 
                    tag.getTagId(), 
                    tag.getTagName() });
    }
}
